package com.fcx.workai.jinchang.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.fcx.workai.jinchang.R;
import com.fcx.workai.jinchang.adapter.HomePagerAdapter;
import com.fcx.workai.jinchang.bean.OssUrlBean;
import com.fcx.workai.jinchang.ui.mine_drawer.MineMainActivity;
import com.hxh.component.basicore.Base.app.AppManager;
import com.hxh.component.basicore.component.mvp.view.BaseActivity;
import com.hxh.component.basicore.ui.loading.CirCleLoadingDialog;
import com.hxh.component.basicore.util.Utils;
import com.hxh.component.business.app.App;
import com.hxh.component.business.arouter.MyAppProvider;
import com.hxh.component.business.arouter.provider.IMainActivityProvider;
import com.hxh.component.business.common.UserInfoDTO;
import com.hxh.component.business.ui.CustomViewPager;
import com.hxh.component.business.ui.MyUtil;
import com.hxh.component.business.ui.bean.UserCompanyListBean;
import com.hxh.component.business.utils.Constant;
import com.hxh.component.ui.alertview.AlertView;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.List;

import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import okhttp3.Call;
import okhttp3.Request;

import static com.hxh.component.business.utils.Constant.ResultCode.RESULT_CODE_COMPANHY;
import static com.hxh.component.business.utils.Constant.ResultCode.RESULT_CODE_MSG;

@Route(path = IMainActivityProvider.KEY)
public class MainActivity extends BaseActivity<MainActivityPresenter> implements MainActivityContract.V {



    CustomViewPager viewpager;

    PageNavigationView mTablayout;

    private HomePagerAdapter mPageAdapter;

    private DrawerLayout drawer;
    private RelativeLayout  rl_setting, rl_company;
    private TextView tv_company;
    private TextView tv_name, tv_mobile;
    private List<UserCompanyListBean.ItemsBean> companyList;
    private String cur_company_name;
    private String cur_company_id;
    private UserCompanyListBean.ItemsBean mChooseCompanyBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main_drawer;
    }

    @Override
    public void initData(Bundle saveInstanceState) {
        initView();
        setLinsener();
        visibe(viewpager);

        if (App.getUserDTO().getUser() != null){
            getP().refreshToken();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }



    private void initView() {
        viewpager = findViewBy(R.id.viewpager);
        mTablayout = findViewBy(R.id.tablayout);
        mPageAdapter = new HomePagerAdapter(getSupportFragmentManager());
        viewpager.setAdapter(mPageAdapter);
        viewpager.setOffscreenPageLimit(3);
        NavigationController navigationController = mTablayout.material()
                .addItem(R.mipmap.ic_home_normal, R.mipmap.ic_home_checked, "首页", getRES_Color(R.color.default_blue))
                .addItem(R.mipmap.ic_message_normal, R.mipmap.ic_message_checked, "消息", getRES_Color(R.color.default_blue))
                .addItem(R.mipmap.ic_mine_normal, R.mipmap.ic_mine_checked, "我的", getRES_Color(R.color.default_blue))
                .dontTintIcon()
                .build();
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        navigationController.setupWithViewPager(viewpager);

        tv_mobile = findViewBy(R.id.tv_mobile);
        drawer = findViewBy(R.id.drawer_layout);

        tv_name = findViewBy(R.id.tv_name);
        rl_setting = findViewBy(R.id.rl_setting);
        rl_company = findViewBy(R.id.rl_company);
        tv_company = findViewBy(R.id.tv_company);

        //禁止抽屉滑动显示
//        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        drawer.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                drawer.getViewTreeObserver().removeOnPreDrawListener(this);
                return false;
            }
        });
    }

    /**
     * 设置数据
     */
    private void setData() {
        UserInfoDTO userinfo = App.getUserDTO();
        if (userinfo != null && userinfo.getUser() != null) {
            tv_name.setText(userinfo.getUser().getUser().getName());
            tv_mobile.setText(userinfo.getUser().getUser().getMobile());
        }

        String mHeadImgUrl = getP().loadimage(null, null, false);

    }

    /**
     * 点击事件
     */
    private void setLinsener() {
        rl_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(MineMainActivity.class, Constant.RouterTag.SHOWTAG, Constant.RouterTag.MINE_SETTING);
            }
        });
        rl_company.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startRouteActivity(MineMainActivity.class, Constant.RouterTag.MINE_CHOOSE_COMPANY, Constant.RouterTag.MINE_CHOOSE_COMPANY);
            }
        });
    }

    @Override
    public MainActivityPresenter newP() {
        return new MainActivityPresenter();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //抽屉展开时优先关闭抽屉
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                AppManager.finshAllActivityButNeedMutilClick();
            }
        }
        return true;
    }

    private AlertView downLoadAlertView;
    private ProgressBar progressBarDl;
    private CirCleLoadingDialog mLoadingDialog;

    @Override
    public void showJiGouResult(UserCompanyListBean bean) {
        companyList = bean.getItems();

        cur_company_id = Utils.SP.getString(Constant.SpTag.COMPANY_ID);
        cur_company_name = Utils.SP.getString(Constant.SpTag.COMPANY_NAME);
        if (!isEmpty(cur_company_id) && !isEmpty(cur_company_name)) {
            UserCompanyListBean.ItemsBean itemsBean = new UserCompanyListBean.ItemsBean();
            itemsBean.setName(cur_company_name);
            itemsBean.setId(cur_company_id);
            mChooseCompanyBean = itemsBean;
        }

        if (!isEmpty(companyList) && isEmpty(cur_company_name)) {
            mChooseCompanyBean = companyList.get(0);
            cur_company_name = mChooseCompanyBean.getName();
            cur_company_id = mChooseCompanyBean.getId();
            Utils.SP.editor().putString(Constant.SpTag.COMPANY_BEAN, JSON.toJSONString(bean)).commit();
            Utils.SP.editor().putString(Constant.SpTag.COMPANY_ID, cur_company_id).commit();
            Utils.SP.editor().putString(Constant.SpTag.COMPANY_NAME, cur_company_name).commit();
        }
        setText(tv_company, cur_company_name);
    }

    @Override
    public void showRefreshTokenResult(boolean isSuccess) {
        if (isSuccess) {
            setData();
            getP().checkUpdate();
            getP().getOssUrl();
            getP().initOss_default();
        } else {
            toastShort("登录失效，请重新登录");
            Utils.SP.editor().remove(Constant.SpTag.COMPANY_NAME).commit();
            Utils.SP.editor().remove(Constant.SpTag.COMPANY_ID).commit();
            Utils.SP.editor().remove(Constant.SpTag.COMPANY_BEAN).commit();
            Utils.SP.editor().clear();
            MyAppProvider.startLoginActivty(Constant.RouterTag.SHOWTAG, Constant.RouterTag
                    .LOGIN_SHOWTYPE_SMSLOGIN);
            App.getUserDTO().setUser(null);
            this.finish();
        }
    }

    @Override
    public void showCheckUpdateResult(String updatestate, final String url, List<String> strs) {
        if (!isEmpty(updatestate)) {
            mLoadingDialog = new CirCleLoadingDialog(this, "");
            View rootView = LayoutInflater.from(this).inflate(R.layout.layout_appupdate, null);
            View downLoadView = LayoutInflater.from(this).inflate(R.layout.layout_downloadtip, null);
            progressBarDl = (ProgressBar) downLoadView.findViewById(R.id.pregressbar);

            final AlertView downLoadTIpView = MyUtil.DialogUtils.showDefaulStyleDialog(downLoadView, false);

            LinearLayout lin_updatedetail = (LinearLayout) rootView.findViewById(R.id.lin_updatedetail);
            ImageView iv_closeButton = (ImageView) rootView.findViewById(R.id.iv_closeButton);
            TextView tv_update = (TextView) rootView.findViewById(R.id.tv_update);
            for (String str : strs) {
                lin_updatedetail.addView(createTextView(str));
            }
            switch (updatestate) {
                case Constant.APPUPDATESTATE_FORCE:
                    gone(iv_closeButton);
                    downLoadAlertView = MyUtil.DialogUtils.showDefaulStyleDialog(rootView, false);
                    break;
                case Constant.APPUPDATESTATE_NOFORCE:
                    visibe(iv_closeButton);
                    downLoadAlertView = MyUtil.DialogUtils.showDefaulStyleDialog(rootView, true);
                    break;
            }
            tv_update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    downLoadAlertView.dismiss();
                    // downLoadTIpView.show();
                    mLoadingDialog.show();
                    getP().downLoadAPK(url, new FileCallBack(App.getAppInitDelegate().getAppCacheDir(), Constant.APPUPDATEFILENAME) {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onBefore(Request request, int id) {
                            super.onBefore(request, id);

                        }

                        @Override
                        public void inProgress(final float progress, long total, int id) {
                            super.inProgress(progress, total, id);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mLoadingDialog.setText(((int) progress) + "%");
                                }
                            });
                        }


                        @Override
                        public void onResponse(File response, int id) {
                            mLoadingDialog.close();
                            Utils.Package.installNormal(App.getAppInitDelegate().getAPKSavePath());
                        }
                    });
                }
            });
            downLoadAlertView.show();
        }
    }

    @Override
    public void showOssResult(OssUrlBean bean) {
        if (bean != null) {
            App.getAppInitDelegate().saveData(Constant.OSSId.OSS_URL, "http://" + bean
                    .getEnd_point());
        }
    }


    private void startRouteActivity(Class newclass, String newtag, String act) {
        Intent intents = new Intent(this, newclass);
        if (Constant.RouterTag.MINE_MSG.equals(act)) {
            intents.putExtra(Constant.RouterTag.SHOWTAG, newtag);
            startActivityForResult(intents, RESULT_CODE_MSG);
        } else if (Constant.RouterTag.MINE_CHOOSE_COMPANY.equals(act)) {
            intents.putExtra(Constant.RouterTag.SHOWTAG, newtag);
            intents.putExtra("choose_company", mChooseCompanyBean);
            startActivityForResult(intents, RESULT_CODE_COMPANHY);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private TextView createTextView(String text) {
        TextView tv = new TextView(this);
        tv.setTextSize(Utils.Dimens.pxToDp(35));
        tv.setTextColor(getRES_Color(R.color.text_gray_6));
        tv.setText(text);
        return tv;
    }

}
